#include "StdAfx.h"
#include "Level.h"
#include "Graphics\DxRenderer.h"
#include "Utility\XmlParser.h"

static const u32 s_uHash_Terrain = 0x39c3ab7a;

Level::Level(const char* szFile)
{
	m_szName = NULL;
	m_pTerrainLayout = NULL;

	Load(szFile);
}


Level::~Level(void)
{
	if( m_szName )
		free(m_szName);

	if( m_pTerrainLayout )
		delete[] m_pTerrainLayout;
}

void Level::Load(const char* szFile)
{
	XmlParser* pParser = new XmlParser();

	if( pParser->LoadFile(szFile) && pParser->HasElement() )
	{
		m_szName = _strdup(pParser->GetValue());

		pParser->FirstChildElement(); //<Data></Data>
		pParser->FirstChildElement();

		while( pParser->HasElement() )
		{
			u32 node = pParser->GetValueAsInt();
			switch(node)
			{
			case s_uHash_Terrain:
				CreateTerrain(pParser);
				break;
			}

			pParser->NextSiblingElement();
		}

		pParser->Parent();
		pParser->Parent();
	}

	delete pParser;
}

void Level::CreateTerrain(XmlParser* pParser)
{
	m_iTerrainWidth = pParser->GetAttributeAsInt("width");
	m_iTerrainHeight = pParser->GetAttributeAsInt("height");
	m_aTerrainModels.SetSize(pParser->GetAttributeAsInt("models"));

	m_iSizePerModel = pParser->GetAttributeAsInt("size");

	pParser->FirstChildElement();

	for(int i = 0; i < m_aTerrainModels.GetNumElements(); i++)
	{
		Model* model = new Model();
		//model->Load(pParser->GetChildValue());
		m_aTerrainModels.Add(model);
		pParser->NextSiblingElement();
	}

	pParser->Parent();


	//create a random grid using the models supplied
	int iSize = m_iTerrainWidth * m_iTerrainHeight;
	m_pTerrainLayout = new int[iSize];
	for(int i = 0; i < iSize; i++)
	{
		int iRand = rand() % m_aTerrainModels.GetNumElements();
		
		m_pTerrainLayout[i] = iRand;
	}
}

void Level::Draw()
{
	int iSize = m_iTerrainWidth * m_iTerrainHeight;
	Vector4 vCenter(m_iSizePerModel * (m_iTerrainWidth * 0.5f), 0.0f, m_iSizePerModel * (m_iTerrainHeight * 0.5f), 1.0f);
	for(int i = 0; i < iSize; i++)
	{
		int iRand = rand() % m_aTerrainModels.GetNumElements();
		Vector4 vPos((i % m_iTerrainWidth) * m_iSizePerModel, 0.0f, (i / m_iTerrainHeight) * m_iSizePerModel, 1.0f);

		vPos -= vCenter;
		vPos.SetW(1.0f);

		Model* model = m_aTerrainModels[m_pTerrainLayout[i]];
		model->SetPosition(vPos);
		model->Draw();
	}
}